% by YLX on 6/10
% Version 2.3
% The Fisrt max_level should be J-1
function expandFor(m, max_level)
    % st = ftimer();
    global J % globals defined in main function
    global seq index PIE % globals definded in findPIE
    level = J - max_level; % level is level of for loop

    %if ~(J > 0) || size(J, 1) == 0
    %    disp('Incorrect J set!');
    %end
    if level > J-1
        PIE(index, 1) = seq(1) - 1;
        PIE(index, J) = m + 1 - seq(J-1);
        for jj=2:J-1
            PIE(index, jj) = seq(jj) - seq(jj-1); 
        end
        %seq2 = [seq, m+1];
        %seq1 = [1, seq];
        %PIE(index, :) = seq2 - seq1;
        % >>> for test
        % fprintf('\t\t\t Saving Seq=\t');
        % disp(seq);
        % fprintf('\t\t\t Saving PIE=\t');
        % disp(PIE(index, :));
        % <<<
        index = index + 1;
        
    else
        if level > 1
            start = seq(level-1);
        else 
            start = 1;
        end
        
        for i = start:m+1
            seq(level) = i;
            % >>> for test
            % for k=1:level-1
            %     fprintf("\t");
            % end
            % fprintf('level= %d ; start = %d ; i = %d \n\n', level, start, i);
            % <<<
            expandFor(m, max_level-1);
        end
    end                                                                                                                                                                                                            
    %global T_expandFor N_expandFor
    %T_expandFor = T_expandFor + ftimer()-st;
    %N_expandFor = N_expandFor + 1;
    return;